package com.example.servlet;

import com.example.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet(name = "LikeArticleServlet", urlPatterns = "/like-article")
public class LikeArticleServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        Integer userId = session != null ? (Integer) session.getAttribute("user_id") : null;
        if (userId == null) {
            resp.sendRedirect("login.jsp");
            return;
        }
        String articleIdStr = req.getParameter("article_id");
        if (articleIdStr == null) {
            resp.sendRedirect("index.jsp");
            return;
        }
        int articleId = Integer.parseInt(articleIdStr);
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement check = conn.prepareStatement("SELECT 1 FROM article_like WHERE user_id=? AND article_id=?")) {
            check.setInt(1, userId);
            check.setInt(2, articleId);
            try (ResultSet rs = check.executeQuery()) {
                if (rs.next()) {
                    // 已点赞，直接返回
                    resp.sendRedirect("index.jsp");
                    return;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 点赞+1并记录
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement like = conn.prepareStatement("UPDATE articles SET likes = likes + 1 WHERE id = ?");
             PreparedStatement record = conn.prepareStatement("INSERT INTO article_like(user_id, article_id) VALUES (?, ?)");) {
            like.setInt(1, articleId);
            like.executeUpdate();
            record.setInt(1, userId);
            record.setInt(2, articleId);
            record.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
        resp.sendRedirect("index.jsp");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("/article");
    }
} 